<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert show-icon title="添加商品信息" type="info" center :closable="false"></el-alert>
      <el-steps :active="index - 0" :space="200" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form :model="addGoodsForm" ref="addGoodsFormRef" :rules="addGoodsFormRules" label-position="top">
        <el-tabs v-model="index" tab-position="left" :before-leave="beforeLeave" @tab-click="tabClick(index)">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="addGoodsForm.goods_cat" :options="cateList" :props="cateProps" @change="handleChange" clearable></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :key="index" v-for="(item, index) in manyList" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals" @change="changeAttr(item.attr_vals)">
                <el-checkbox :label="vals" v-for="(vals, indexs) in item.attr_vals" :key="indexs" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyList" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-form-item label="商品图片" prop="pics">
              <el-upload :action="uploadUrl" :headers="headerObj" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture" :on-success="handleSuccess">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
            <el-dialog :visible.sync="isPreviewDialogVisible" width="50%" title="预览">
              <img width="100%" :src="previewImgUrl" />
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce"/>
            <el-button type="primary" class="addBtn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      info: {},
      type: '',
      index: '0',
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        pics: [
          { required: true, message: '请选择商品图片', trigger: 'change' }
        ]
      },
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      cateList: [],
      manyList: [],
      onlyList: [],
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      isPreviewDialogVisible: false,
      previewImgUrl: ''
    }
  },
  created() {
    const obj = this.$route.params
    const num = Object.keys(obj)
    if(num.length !== 0) {
      this.type = 'edit'
      obj.goods_cat = []
      obj.pics = []
      obj.attrs = []
      this.addGoodsForm = obj
      console.log(this.addGoodsForm)
    }else {
      this.type = 'add'
    }
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if(res.meta.status !== 200) return this.$message({ type: 'error', message: '获取分类列表失败', duration: 2000 })
      this.cateList = res.data
    },
    handleChange(val) {
      if(this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
      }
    },
    beforeLeave(activeName, oldActiveName) {
      if(oldActiveName === '0') {
        if(this.addGoodsForm.goods_name === '' || this.addGoodsForm.goods_cat.length !== 3) {
          this.$refs.addGoodsFormRef.validateField(['goods_name', 'goods_cat'])
          return false
        }
      }
      if(oldActiveName === '3' && activeName - 0 > oldActiveName - 0) {
        if(this.addGoodsForm.pics.length < 1) {
          this.$message({ type: 'warning', message: '请添加商品图片', duration: 2000 })
          return false
        }
      }
    },
    async tabClick(index) {
      if(index === '1') {
        const { data: res } = await this.$http.get(`categories/${this.getCateId}/attributes`, { params: { sel: 'many' } })
        if(res.meta.status !== 200) return this.$message({ type: 'error', message: '获取分类属性失败', duration: 2000 })
        this.manyList = res.data
        console.log(this.manyList)
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        })
      }else if(index === '2') {
        const { data: res } = await this.$http.get(`categories/${this.getCateId}/attributes`, { params: { sel: 'only' } })
        if(res.meta.status !== 200) return this.$message({ type: 'error', message: '获取分类参数失败', duration: 2000 })
        this.onlyList = res.data
        console.log(this.onlyList)
      }
    },
    handlePreview(file) {
      this.previewImgUrl = file.response.data.url
      this.isPreviewDialogVisible = true
    },
    handleRemove(file) {
      const path = file.response.data.tmp_path
      const index = this.addGoodsForm.pics.findIndex(item => item.pics === path)
      this.addGoodsForm.pics.splice(index, 1)
    },
    handleSuccess(res) {
      const path = {
        pic: res.data.tmp_path
      }
      this.addGoodsForm.pics.push(path)
    },
    addGoods() {
      this.$refs.addGoodsFormRef.validate(async (valid, msg) => {
        if(!valid) {
          for(const key in msg) {
            return this.$message({ type: 'error', message: msg[key][0].message, duration: 2000 })
          }
        }
        this.manyList.forEach(item => {
          const manyObj = {
            attr_id: item.attr_id,
            attr_vals: item.attr_vals
          }
          this.addGoodsForm.attrs.push(manyObj)
        })
        this.onlyList.forEach(item => {
          const onlyObj = {
            attr_id: item.attr_id,
            attr_vals: item.attr_vals
          }
          this.addGoodsForm.attrs.push(onlyObj)
        })
        console.log(this.addGoodsForm)
        this.addGoodsForm.goods_name = this.addGoodsForm.goods_name.trim()
        const formData = _.cloneDeep(this.addGoodsForm)
        formData.goods_cat = formData.goods_cat.join(',')
        if(this.type === 'add') {
          const { data: res } = await this.$http.post('goods', formData)
          if(res.meta.status !== 201) return this.$message({ type: 'error', message: res.meta.msg, duration: 2000 })
          this.$message({ type: 'success', message: '添加商品成功', duration: 2000 })
        }else if(this.type === 'edit') {
          const { data: res } = await this.$http.put('goods/' + formData.goods_id, formData)
          console.log(res)
          if(res.meta.status !== 200) return this.$message({ type: 'error', message: res.meta.msg, duration: 2000 })
          this.$message({ type: 'success', message: '修改商品成功', duration: 2000 })
        }
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    getCateId() {
      if(this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
  .el-steps {
    margin: 15px auto;
  }
  .el-checkbox{
    margin: 0 10px 0 0!important;
  }
  .addBtn {
    margin-top: 10px;
  }
  /deep/ .el-input__inner{
    width: 98%;
  }
  .el-card {
    min-height: 600px;
  }
</style>
